package com.zh.harmony.handlerthread.sample.service;

import com.zh.harmony.handlerthread.sample.Constant;
import com.zh.harmony.handlerthread.sample.util.HiLogUtil;
import com.zh.harmony.handlerthread.sample.util.TextUtils;
import com.zh.harmony.handlerthread.sample.util.ToastUtil;
import com.zh.harmony.intentservice.IntentService;
import ohos.aafwk.content.Intent;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * 下载服务
 */
public class DownloadService extends IntentService {
    private final OkHttpClient mOkHttpClient;

    public DownloadService() {
        super("DownLoadService");
        mOkHttpClient = new OkHttpClient.Builder().build();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent == null) {
            return;
        }
        ArrayList<String> urls = intent.getSerializableParam(Constant.URLS);
        if (urls == null || urls.isEmpty()) {
            return;
        }
        //下载文件
        for (String url : urls) {
            try {
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = mOkHttpClient.newCall(request);
                Response response = call.execute();
                ResponseBody body = response.body();
                if (body == null) {
                    return;
                }
                InputStream inputStream = body.byteStream();
                //保存到磁盘
                String filePath = save2Local(
                        getContext().getExternalCacheDir().getAbsolutePath(),
                        System.currentTimeMillis() + "_image.jpg",
                        inputStream
                );
                if (!TextUtils.isEmpty(filePath)) {
                    HiLogUtil.debug("保存的文件路径：" + filePath);
                    ToastUtil.toast(getContext(), "保存成功");
                } else {
                    ToastUtil.toast(getContext(), "保存失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存PixelMap到本地
     *
     * @return 保存后的文件路径，保存失败则为null
     */
    private String save2Local(String dirPath, String fileName, InputStream inputStream) {
        //创建目录
        if (makeFileDirIfNotExist(dirPath)) {
            File file = new File(dirPath, fileName);
            try {
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                return file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 创建目录文件夹
     */
    private boolean makeFileDirIfNotExist(String dirPath) {
        File file = new File(dirPath);
        if (file.exists()) {
            return true;
        } else {
            return file.mkdirs();
        }
    }
}